package com.isa.androidwebtrans;

import java.io.File;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.appcompat.R.anim;
import android.view.View;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.isa.app.MyApp;
import com.isa.http.HttpAssist;
import com.isa.http.HttpClientTest;
import com.isa.util.Arguments;
import com.isa.util.Myhandler;

public class MainActivity extends Activity {

	private Button btnUpload;
	private Button btnChangeKey;
	private Button btnCheck;
	private Button btnLogin;
	private Button btnDownload;
	private Button btnManage;

	public String response;
	private byte[] pubKey;
	private byte[] priKey;
	private byte[] symKey;

	Myhandler myhandler;
	Handler handler;
	HttpClient httpClient;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		myhandler = Myhandler.getInstance();
		handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				if (msg.what == Arguments.MESSAGE_LOGIN_OK) {
					btnChangeKey.setVisibility(View.VISIBLE);
					btnLogin.setVisibility(View.GONE);
					btnUpload.setVisibility(View.VISIBLE);
					btnDownload.setVisibility(View.VISIBLE);
					btnManage.setVisibility(View.VISIBLE);
				}
			}
		};

		btnUpload = (Button) findViewById(R.id.btnUpload);
		btnChangeKey = (Button) findViewById(R.id.btnChangeKey);
		btnCheck = (Button) findViewById(R.id.btnCheck);
		btnLogin = (Button) findViewById(R.id.btnLogin);
		btnDownload = (Button) findViewById(R.id.btnDownload);
		btnManage = (Button) findViewById(R.id.btnManage);
		httpClient = new DefaultHttpClient();

		// 隐藏按钮
		btnUpload.setVisibility(View.GONE);
		btnChangeKey.setVisibility(View.GONE);
		btnDownload.setVisibility(View.GONE);
		btnManage.setVisibility(View.GONE);
		if (!Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			Toast.makeText(this, "SD卡不可以被访问，此应用无法正常工作！", Toast.LENGTH_SHORT)
					.show();
			btnLogin.setClickable(false);
		}
		File f = new File(Arguments.ROOT_PATH);
		if (!f.exists())
			f.mkdir();

		// 上传文件
		btnChangeKey.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				setKeyChangeWay();
			}
		});
		
		
		//点击跳转Activity进行管理
		btnManage.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent i = new Intent(MainActivity.this,ManageActivity.class);
				startActivity(i);
				
			}
		});
		
		

		// 检查是否连接
		btnCheck.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				new Thread() {
					@Override
					public void run() {
						try {
							response = HttpClientTest
									.sendGet(Arguments.WEB_LOGIN_SERVLET,
											"action=check");
							Message msg = new Message();
							msg.obj = response;
							msg.what = Arguments.MESSAGE_CONNECT_OK;
							myhandler.sendMessage(msg);
						} catch (Exception e) {
							e.printStackTrace();
							myhandler
									.sendEmptyMessage(Arguments.MESSAGE_CONNECT_BAD);
						}
					}
				}.start();

			}
		});
		btnUpload.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				try {
					Intent intent = new Intent(MyApp.getContext(),
							ChooseFileActivity.class);
					intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // intent的startActivity需添加
					MyApp.getContext().startActivity(intent);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
		btnLogin.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				showLogin(v);
			}
		});
		// 下载文件
		btnDownload.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				try {
					final View downDialog = getLayoutInflater().inflate(
							R.layout.download_list, null);
					final ListView downList = (ListView) downDialog
							.findViewById(R.id.downlv);

					new Thread() {
						@Override
						public void run() {
							response = getDownList();

						}
					}.start();
					Thread.sleep(500);
					final List<String> list = new ArrayList<String>();
					if (response != null && response.length() != 0) {
						String[] str = response.split(",");
						for (String s : str) {
							list.add(s);
						}
					}
					downList.setOnItemClickListener(new OnItemClickListener() {

						@Override
						public void onItemClick(AdapterView<?> parent,
								View view, int position, long id) {
							final int _position = position;
							new Thread() {
								public void run() {
									try {
										HttpAssist.downLoad(
												Arguments.WEB_DOWNLOAD
														+ "?filename="
														+ list.get(_position),
												Arguments.ROOT_PATH+"/"+list.get(_position));
										myhandler
												.sendEmptyMessage(Arguments.MESSAGE_DOWNLOAD_OK);

									} catch (Exception e) {
										e.printStackTrace();
										myhandler
												.sendEmptyMessage(Arguments.MESSAGE_DOWNLOAD_WRONG);
									}

								};
							}.start();
						}
					});
					ListAdapter adapter = new ArrayAdapter(MainActivity.this,
							android.R.layout.simple_list_item_1, list);

					downList.setAdapter(adapter);

					new AlertDialog.Builder(MainActivity.this)
							.setTitle("选择要下载的文件").setView(downDialog).setNegativeButton("取消", null).show();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});

	}

	private String getDownList() {
		String result = null;
		try {
			result = HttpClientTest.sendGet(Arguments.WEB_DOWNLOAD,
					"action=getfilelist");

		} catch (Exception e) {
			e.printStackTrace();
			myhandler.sendEmptyMessage(Arguments.MESSAGE_DOWNLOADLIST_WRONG);
		}
		return result;

	}

	// 提示重新登录
	@Override
	protected void onRestart() {
		new AlertDialog.Builder(MainActivity.this).setTitle("Warning")
				.setMessage("账号已经退出，请重新登录！！！").setPositiveButton("确定", null)
				.show();
		super.onRestart();
	}

	@Override
	protected void onStop() {
		btnChangeKey.setVisibility(View.GONE);
		btnLogin.setVisibility(View.VISIBLE);
		btnUpload.setVisibility(View.GONE);
		btnDownload.setVisibility(View.GONE);
		btnManage.setVisibility(View.GONE);
		super.onPause();
	}

	public void showLogin(View v) {

		// 加载登录界面
		final View loginDialog = getLayoutInflater().inflate(R.layout.login,
				null);
		// 使用对话框供用户登录系统
		new AlertDialog.Builder(MainActivity.this).setTitle("登录系统")
				.setView(loginDialog)
				.setPositiveButton("登录", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// 获取用户输入的用户名、密码
						final String name = ((EditText) loginDialog
								.findViewById(R.id.name)).getText().toString();
						final String pass = ((EditText) loginDialog
								.findViewById(R.id.pass)).getText().toString();
						new Thread() {
							public void run() {
								try {
									String param = "name=" + name + "&pass="
											+ pass + "&action=login";
									String result = HttpClientTest.sendGet(
											Arguments.WEB_LOGIN_SERVLET, param);
									if (result.equals("OK")) {
										Message msg = new Message();
										msg.what = Arguments.MESSAGE_LOGIN_OK;
										msg.obj = loginDialog;
										myhandler.sendMessage(msg);
										handler.sendEmptyMessage(Arguments.MESSAGE_LOGIN_OK);
									} else {
										myhandler
												.sendEmptyMessage(Arguments.MESSAGE_LOGIN_WRONG);
									}

								} catch (Exception e) {
									e.printStackTrace();
									myhandler
											.sendEmptyMessage(Arguments.MESSAGE_LOGIN_NETWRONG);
								}
							};
						}.start();
					}
				}).setNegativeButton("取消", null).show();
	}

	// 点击交换密钥按钮执行
	public void setKeyChangeWay() {
		try {
			Intent intent = new Intent(MyApp.getContext(),
					ChooseKeyActivity.class);
			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // intent的startActivity需添加
			MyApp.getContext().startActivity(intent);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
